import React from "react";
import ReactDOM from "react-dom";
import "./index.scss";

const num = 3;

// 落子
function setPiece(isX) {
  return isX ? "X" : "O";
}

// 判断胜利，返回胜利方
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return { winner: squares[a], lines: lines[i] };
    }
  }
  return null;
}

// 棋盘
function Board(props) {
  const { winner,squares, onClick } = props;

  function handleClick(i) {
    onClick(i);
  }

  function renderSquare(i) {
    return (
      <button key={i} className={(winner&&(winner.lines.indexOf(i)>-1))?'square-winner':'square'} onClick={() => handleClick(i)}>
        {squares[i]}
      </button>
    );
  }

  let board = [];
  for (var i = 0; i < num; i++) {
    var boardRow = [];
    for (var j = 0; j < num; j++) {
      boardRow.push(renderSquare(i * num + j));
    }
    board.push(
      <div className="board-row" key={i}>
        {boardRow}
      </div>
    );
  }
  return <div>{board}</div>;
}

class Game extends React.Component {
  state = {
    // 历史记录
    historyList: [
      {
        squares: Array(9).fill(null),
      },
    ],
    // 当前记录
    stepNumber: 0,
    // 当前落子方
    isX: true,
    // 是否倒序
    isSort: false,
  };

  handleClick = (i) => {
    const { historyList, isX, stepNumber } = this.state;

    const squares = historyList[stepNumber].squares.slice();
    if (squares[i] || calculateWinner(squares)) return;

    squares[i] = setPiece(isX);
    const curHistoryList = historyList.slice(0, stepNumber + 1);

    this.setState({
      historyList: curHistoryList.concat([
        {
          squares: squares,
          position: `${(i / 3 + 1) | 0}行${((i % 3) + 1) | 0}列`,
          isX,
        },
      ]),
      isX: !isX,
      stepNumber: curHistoryList.length,
    });
  };

  jumpTo = (move) => {
    this.setState({
      stepNumber: move,
      isX: move % 2 === 0,
    });
  };

  handleHistorySort = () => {
    const { isSort } = this.state;

    this.setState({
      isSort: !isSort,
    });
  };

  render() {
    const { historyList, isX, stepNumber, isSort } = this.state;
    const squares = historyList[stepNumber].squares;

    const winner = calculateWinner(squares);

    let status = "下一位选手: " + setPiece(isX)
    if (winner) {
      status = "胜利者: " + winner.winner
    } else if (stepNumber === num*num){
      status = "平局！"
    }

    const historyListTmp = historyList.map((step, move) => {
      const desc = move
        ? `# ${move} 历史步骤 ${step.position} ${setPiece(step.isX)}`
        : "游戏开始";
      return (
        <div key={move}>
          <button
            className={
              move === stepNumber ? "historyActive" : "historyInactive"
            }
            onClick={() => this.jumpTo(move)}
          >
            {desc}
          </button>
        </div>
      );
    });

    const moves = isSort ? historyListTmp.reverse() : historyListTmp;

    return (
      <>
        <div className="game">
          <div className="bg"></div>
          <div className="game-info">{status}</div>
          <div className="game-board">
            <Board winner={winner} squares={squares} isX={isX} onClick={this.handleClick} />
          </div>
        </div>
        <button
          className={[
            "game-history-sort",
            isSort ? "game-history-sort-active" : "game-history-sort-inactive",
          ].join(" ")}
          onClick={this.handleHistorySort}
        >
          {isSort ? "↓" : "↑"}
        </button>
        <div className="game-history">{moves}</div>
      </>
    );
  }
}

// ========================================

ReactDOM.render(<Game />, document.getElementById("root"));
